package com.qding.park.adapter.ark.adapter.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qding.park.adapter.ark.adapter.config.ARKConfig;
import com.qding.park.adapter.ark.adapter.constant.MethodConstant;
import com.qding.park.adapter.ark.adapter.entity.ResponseMsg;
import com.qding.park.adapter.ark.adapter.enums.InvitationEventEnum;
import com.qding.park.adapter.ark.adapter.enums.RespCodeEnums;
import com.qding.park.adapter.ark.adapter.util.Helper;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.core.network.HttpUtil;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.manager.pojo.ap.ApPark;
import com.qding.park.target.common.adapter.ParkAdapter;
import com.qding.park.target.common.entity.AdParkConnStatu;
import com.qding.park.target.common.entity.AdParkInfo;
import com.qding.park.target.common.entity.AdcarInParkTag;
import com.qding.park.target.common.enums.ParkConnStatuEnum;

/**
 * @ClassName ParkAdapterImpl
 * @Description TODO(车场信息接口实现)
 * @author LeiYang
 * @Date 2017年5月8日 下午4:41:37
 * @version 1.0.0
 */
@Service("parkAdapter_13")
public class ParkAdapterImpl implements ParkAdapter {

    private static final Logger _log = LoggerFactory.getLogger(ParkAdapterImpl.class);

    /*
     * (非 Javadoc) Description:查询车场剩余临停车位数
     * @see com.qding.park.target.common.adapter.ParkAdapter#getTempStopNum(java.lang.String)
     */
    @Override
    public AdParkInfo getTempStopNum(String parkCode, String userId) throws NetWorkException, AdapterException {

        String url = ARKConfig.getAdapterUrl();
        String urlMethod=Helper.createUrlAddress(url, MethodConstant.GET_PARKINFO);

        Map<String, String> params = new HashMap<String, String>();
        params.put("personId", userId);
        params.put("parkId", parkCode);
        try {
            String result = HttpUtil.doPost(urlMethod, params);
            ResponseMsg response = Helper.analysisResponse(result);

            if (!RespCodeEnums.SUCCESS.getValue().equals(response.getCode())) {
                // 失败
                ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                        AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), response.getMsg(),
                        "personId:" + userId + "," + "parkId:" + parkCode);

                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        exceptionMessage);
            }

            JSONObject datajson = (JSONObject) response.getData();
            String totalParkingSpaces = datajson.getString("totalParkingSpaces");
            String remainingParkingSpaces = datajson.getString("remainingParkingSpaces");

            AdParkInfo adParkInfo = new AdParkInfo();
            adParkInfo.setTotalSpace(Integer.valueOf(totalParkingSpaces));
            adParkInfo.setRestSpace(Integer.valueOf(remainingParkingSpaces));
            return adParkInfo;

        } catch (NetWorkException | IOException e) {
            _log.error(e.getMessage(), e);
            ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                    AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟接口网络暖异常",
                    "personId:" + userId + "," + "parkId:" + parkCode);
            throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), e, exceptionMessage);
        }
    }

    /*
     * (非 Javadoc) Description:车辆是否在车场里面
     * @see com.qding.park.target.common.adapter.ParkAdapter#carInParkTag(java.lang.String, java.lang.String,
     * java.lang.String)
     */
    @Override
    public AdcarInParkTag carInParkTag(String carNum, String parkCode, String userId) {
        String url = ARKConfig.getAdapterUrl();
        String urlMethod=Helper.createUrlAddress(url, MethodConstant.GET_PARKIN_BY_CAR);

        Map<String, String> params = new HashMap<String, String>();
        params.put("personId", userId);
        params.put("parkId", parkCode);
        params.put("carNo", carNum);
        try {
            String result = HttpUtil.doPost(urlMethod, params);
            ResponseMsg response = Helper.analysisResponse(result);

            if (!RespCodeEnums.SUCCESS.getValue().equals(response.getCode())) {
                // 失败
                ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                        AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), response.getMsg(),
                        "personId:" + userId + "," + ",parkId:" + parkCode + ",carNo:" + carNum);

                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        exceptionMessage);
            }

            JSONObject datajson = (JSONObject) response.getData();
            String isInPark = datajson.getString("isInPark");
            String inParkTime = datajson.getString("inParkTime");

            AdcarInParkTag dcarInParkTag = new AdcarInParkTag();
            dcarInParkTag.setInOutFlag("0".equals(isInPark) ? true : false);
            dcarInParkTag.setParkInTime(DateUtils.parseDate(inParkTime, DateUtils.DATE_FORMAT_DATETIME));
            return dcarInParkTag;

        } catch (NetWorkException | IOException e) {
            _log.error(e.getMessage(), e);
            ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                    AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟接口网络暖异常",
                    "personId:" + userId + "," + ",parkId:" + parkCode + ",carNo:" + carNum);
            throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), e, exceptionMessage);
        }
    }

    @Override
    public AdParkConnStatu getParkConnStatu(String parkCode, String userId) {
        String url = ARKConfig.getAdapterUrl();
        String urlMethod=Helper.createUrlAddress(url, MethodConstant.GET_PARK_CONNECTION_STATUS);

        Map<String, String> params = new HashMap<String, String>();
        List<String> parkIdList = new ArrayList<String>();
        parkIdList.add(parkCode);
        params.put("personId", userId);
        params.put("parkIds", JSON.toJSONString(parkIdList));
        try {
            String result = HttpUtil.doPost(urlMethod, params);
            ResponseMsg response = Helper.analysisResponse(result);

            if (!RespCodeEnums.SUCCESS.getValue().equals(response.getCode())) {
                // 失败
                ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                        AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), response.getMsg(),
                        "personId:" + userId + "," + ",parkId:" + parkCode);

                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        exceptionMessage);
            }

            JSONArray dataArray = (JSONArray) response.getData();
            JSONObject datajson = dataArray.getJSONObject(0);

            String parkId = datajson.getString("parkId");
            String parkName = datajson.getString("parkName");
            String parkStatus = datajson.getString("parkStatus");
            String lastOnlineTime = datajson.getString("lastOnlineTime");

            AdParkConnStatu adParkConnStatu = new AdParkConnStatu();
            adParkConnStatu
                    .setConnStatu("0".equals(parkStatus) ? ParkConnStatuEnum.ON_LINE : ParkConnStatuEnum.OFF_LINE);
            adParkConnStatu.setParkCode(parkId);
            adParkConnStatu.setParkName(parkName);
            adParkConnStatu.setLastRequestTime(DateUtils.parseDate(lastOnlineTime, DateUtils.DATE_FORMAT_DATETIME));
            return adParkConnStatu;

        } catch (NetWorkException | IOException e) {
            _log.error(e.getMessage(), e);
            ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                    AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟接口网络暖异常",
                    "personId:" + userId + "," + ",parkId:" + parkCode);
            throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), e, exceptionMessage);
        }
    }

}
